from rest_framework import serializers
from django.db import transaction
from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification

from apps.goods.models import SpecificationOption,SKUSpecification
class SKUSpecificationSerializer(serializers.ModelSerializer):
    spec_id=serializers.IntegerField()
    option_id=serializers.IntegerField()
    class Meta:
        model=SKUSpecification
        fields=['spec_id','option_id']

class SkuSerializer(serializers.ModelSerializer):
    spu_id=serializers.IntegerField()
    category_id=serializers.IntegerField()
    spu=serializers.StringRelatedField(read_only=True)
    category=serializers.StringRelatedField(read_only=True)
    specs=SKUSpecificationSerializer(many=True)
    class Meta:
        model=SKU
        fields='__all__'

    def create(self, validated_data):
        specs=validated_data.pop('specs')
        with transaction.atomic():
            save_id=transaction.savepoint()
            try:
                sku=SKU.objects.create(**validated_data)
                for spec in specs:
                    SKUSpecification.objects.create(sku=sku,**spec)
            except Exception:
                transaction.savepoint_rollback(save_id)
            else:
                transaction.savepoint_commit(save_id)
            return sku

    def update(self, instance, validated_data):
        specs=validated_data.pop('specs')
        with transaction.atomic():
            savepoint=transaction.savepoint()
            try:
                super().update(instance, validated_data)
                for spec in specs:
                    SKUSpecification.objects.filter(sku=instance,spec_id=spec.get('spec_id')).update(option_id=spec.get('option_id'))
            except Exception:
                transaction.savepoint_rollback(savepoint)
            else:
                transaction.savepoint_commit(savepoint)
        return instance

class SkuCategoriesSerializer(serializers.ModelSerializer):

    class Meta:
        model=GoodsCategory
        fields='__all__'

class SpuSerializer(serializers.ModelSerializer):

    class Meta:
        model=SPU
        fields=['id','name']


class SpecificationOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model=SpecificationOption
        fields='__all__'


class SPUSpecificationSerializer(serializers.ModelSerializer):
    options=SpecificationOptionSerializer(many=True)
    class Meta:
        model=SPUSpecification
        fields='__all__'